﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web.UI;
using visinia.SmartEngine;

public partial class ClientScripts_media_library_media_library : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string folder = Request.QueryString["Folder"];
        Populate(Server.MapPath(WebRoots.GetResourcesRoot));
        if (!string.IsNullOrEmpty(folder))
            BindImageList(folder);
        else
        {
            BindImageList(Directories.Items[0].Value);
        }
    }
    private void Populate(string path)
    {
        DirectoryInfo dir = new DirectoryInfo(path);
        if (dir.Exists)
        {
            Directories.Items.Add("\\");
            GetDirectories(dir.GetDirectories(), dir.FullName);
        }
    }

    private void GetDirectories(DirectoryInfo[] subDirs, string path)
    {
        foreach (DirectoryInfo subDir in subDirs)
        {            
            if ((subDir.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
                continue;
            DirectoryInfo[] subSubDirs;
            Directories.Items.Add(subDir.FullName.Substring(path.Length));
            subSubDirs = subDir.GetDirectories();
            if (subSubDirs.Length != 0)
            {
                GetDirectories(subSubDirs, path);
            }
        }
    }

    private void BindImageList(string folder)
    {
        StringBuilder sb = new StringBuilder();
        string path = Server.MapPath(WebRoots.GetResourcesRoot);
        if (folder != "\\")
            path += folder;
        List<string> files = new List<string>();
        files.AddRange(Directory.GetFiles(path, "*.jpg"));
        files.AddRange(Directory.GetFiles(path, "*.gif"));
        files.AddRange(Directory.GetFiles(path, "*.png"));
        files.AddRange(Directory.GetFiles(path, "*.bmp"));
        sb.Append("<ul id=\"FileList\">");
        foreach (string file in files)
        {
            string name = file.Substring((file.LastIndexOf('\\') + 1));
            string fullname = name;
            if (folder != "\\")
                fullname = folder + "/" + name;
            sb.Append("<li><img alt=\"\" src=\"" + WebRoots.GetWebRoot + "image.axd?picture=" + fullname + "\" title=\"" + fullname + "\" width=\"20px\" height=\"20px\" /><span id=\"FileName\">" + name + "</span></li>");
        }
        sb.Append("</ul>");
        LiteralControl filelist = new LiteralControl(sb.ToString());
        FileListContainer.Controls.Add(filelist);
    }
}
